package com.kreao.korean.config;

import com.kreao.korean.infrastructure.service.DatabaseMigrationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

/**
 * 数据库迁移自动执行配置
 * 在应用启动时自动检查并执行未执行的迁移脚本
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class DatabaseMigrationConfig {

    private final DatabaseMigrationService migrationService;

    @Value("${migration.enabled:true}")
    private boolean migrationEnabled;

    @Value("${migration.auto-execute:true}")
    private boolean autoExecute;

    /**
     * 应用启动时自动执行数据库迁移
     * 使用@Order(1)确保在其他初始化任务之前执行
     */
    @Bean
    @Order(1)
    public CommandLineRunner databaseMigrationRunner() {
        return args -> {
            if (!migrationEnabled) {
                log.info("数据库迁移功能已禁用");
                return;
            }

            if (!autoExecute) {
                log.info("自动执行数据库迁移已禁用，请手动执行");
                return;
            }

            try {
                log.info("=================================");
                log.info("开始启动时数据库迁移检查...");
                log.info("=================================");
                
                migrationService.migrate();
                
                log.info("=================================");
                log.info("数据库迁移检查完成");
                log.info("=================================");
                
            } catch (Exception e) {
                log.error("=================================");
                log.error("启动时数据库迁移失败！应用将继续启动但可能存在数据库结构问题", e);
                log.error("=================================");
                
                // 不抛出异常，允许应用继续启动
                // 但会记录错误，管理员可以手动处理
            }
        };
    }
} 